<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import {
  getCategory,
  addCategory,
  updateCategory,
  delCategory,
} from "@/service/category";
import type { Category } from "@/types/category";
import {
  type TableColumnData,
  type FormInstance,
  Button,
  Message,
  Modal,
} from "@arco-design/web-vue";
import { h } from "vue";
// 查询条件
const filters = reactive({
  name: "",
});

// 表格数据
const categories = ref<Category[]>([]);
// 加载状态
const loading = ref(false);

// 表格列定义
const columns = <TableColumnData[]>[
  { title: "名称", dataIndex: "name", width: 140 },
  { title: "描述", dataIndex: "description" },
  {
    title: "操作",
    key: "option",
    render: (row: any) => {
      return h("div", [
        h(
          Button,
          {
            onClick: () => onOpenModal("编辑", row.record),
          },
          () => "编辑"
        ),
        h(
          Button,
          {
            onClick: () => handleDel(row.record.id),
            status: "danger",
            style: {
              "margin-left": "4px",
            },
          },
          () => "删除"
        ),
      ]);
    },
  },
];

// 获取类别选项
const fetchCategories = () => {
  loading.value = true;
  try {
    getCategory({
      ...filters,
      page: pagination.page,
      pageSize: pagination.pageSize,
    }).then((res) => {
      categories.value = res.data.list;
      pagination.total = res.data.total;
    });
  } catch (e) {
    console.error("加载类别失败", e);
  } finally {
    loading.value = false;
  }
};
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
});

const handlePageChange = (page: number) => {
  pagination.page = page;
  fetchCategories();
};

const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize;
  pagination.page = 1;
  fetchCategories();
};

// 查询
const onSearch = () => {
  pagination.page = 1;
  fetchCategories();
};

// 重置
const onReset = () => {
  filters.name = "";
};

onMounted(() => {
  fetchCategories();
});

const modalVisiable = ref(false);
const cId = ref<number>();
const onOpenModal = (type: string, row?: Category) => {
  formRef.value?.clearValidate();
  formRef.value?.resetFields();
  modalForm.name = "";
  modalForm.description = "";
  modalTitle.value = type;
  if (type === "编辑") {
    if (!row) return;
    modalForm.name = row.name;
    modalForm.description = row.description;
    cId.value = row.id;
  } else {
    cId.value = undefined;
  }
  modalVisiable.value = true;
};
const modalTitle = ref("新增");

const handleCancelModal = () => {
  modalVisiable.value = false;
};
const handleOkModal = () => {
  formRef.value?.validate().then((r: any) => {
    if (r) return;
    const isAdd = modalTitle.value === "新增";
    const action = isAdd
      ? addCategory(modalForm)
      : updateCategory({ ...modalForm, id: cId.value });
    action.then((res) => {
      Message.success(res.message);
      onSearch();
      modalVisiable.value = false;
    });
  });
};

const handleDel = (id: number) => {
  Modal.confirm({
    title: "删除确认",
    content: "确定要删除该货品类别吗？",
    onOk: () => {
      delCategory(id).then((res) => {
        Message.success(res.message);
        onSearch();
      });
    },
  });
};

const modalForm = reactive({
  name: "",
  description: "",
});

const rules = {
  name: [{ required: true, message: "请输入货品名称" }],
};

const formRef = ref<FormInstance>();
</script>

<template>
  <div class="good-page">
    <!-- 查询区域 -->
    <a-card class="search-card">
      <a-form :model="filters" layout="inline">
        <a-form-item label="类别名称">
          <a-input
            v-model="filters.name"
            placeholder="请输入货品类别"
            style="width: 200px"
            allow-clear
          />
        </a-form-item>
        <a-form-item>
          <a-button type="secondary" @click="onOpenModal('新增')">
            <template #icon>
              <IconPlus></IconPlus>
            </template>
            添加货品类别
          </a-button>
          <a-button style="margin-left: 8px" type="primary" @click="onSearch"
            >查询</a-button
          >
          <a-button style="margin-left: 8px" @click="onReset">重置</a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 表格区域 -->
    <div class="table-wrapper">
      <a-table
        :columns="columns"
        :data="categories"
        :pagination="{
          ...pagination,
          showTotal: true,
          showPageSize: true,
        }"
        :scroll="{ y: '100%' }"
        :loading="loading"
        row-key="id"
        @page-change="handlePageChange"
        @pageSize-change="handlePageSizeChange"
      />
    </div>

    <!-- 添加或编辑 -->
    <a-modal
      :visible="modalVisiable"
      :title="modalTitle"
      @ok="handleOkModal"
      @cancel="handleCancelModal"
    >
      <a-form :model="modalForm" :rules="rules" ref="formRef">
        <a-form-item label="货品名称" field="name">
          <a-input
            v-model:modelValue="modalForm.name"
            placeholder="请输入货品名称"
          ></a-input>
        </a-form-item>
        <a-form-item label="描述">
          <a-input
            v-model:modelValue="modalForm.description"
            placeholder="请输入货品描述"
          ></a-input>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped lang="less">
.good-page {
  display: flex;
  flex-direction: column;
  height: calc(100vh - (58px + 24px + 70px));
  overflow: hidden;
  .search-card {
    margin-bottom: 16px;
  }
  .table-wrapper {
    flex: 1;
    min-height: 0;
  }
}
</style>
